package com.henry.db.migrate.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeUtil {
	/**
	 * 把对象序列化为byte数组
	 * @param object
	 * @return
	 * @throws IOException
	 */
	public static byte[] serializeObject(Object object) throws IOException{
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(os);
		oos.writeObject(object);
		oos.flush();
		return os.toByteArray();
	}
	
	/**
	 * 反序列化
	 * @param buf
	 * @return
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	
	
	public static <T> T deserializeObject(byte[] buf) throws IOException,ClassNotFoundException{
		ByteArrayInputStream is = new ByteArrayInputStream(buf);
		ObjectInputStream ois = new ObjectInputStream(is);
		@SuppressWarnings("unchecked")
		T t = (T)ois.readObject();
		return t;
	}
	
	/*private void testSerilizeObject() throws SQLException{
		SimpleSerialRuntime serialRuntime = new SimpleSerialRuntime();
		serialRuntime.setId("xxx");
		
		Connection conn = DBUtil.getDataSource().getConnection();
		QueryRunner runner = new QueryRunner();
		String sql = "INSERT INTO T_BAT_TSK_INF(TSK_ID,SER_CTX,CRE_TIM)VALUES(?,?,?)";
		try {
			conn.setAutoCommit(true);
			runner.update(conn,sql, System.currentTimeMillis()+"",SerializeUtil.serializeObject(serialRuntime),new Timestamp(System.currentTimeMillis()));
		}catch(Exception e){
			e.printStackTrace();
		}
	}*/

}
